import torch
from torch import nn

from einops import rearrange, repeat
from einops.layers.torch import Rearrange

# helpers

def pair(t):
    return t if isinstance(t, tuple) else (t, t)

# classes

'''
import torch
from vit_pytorch import ViT

v = ViT(
    image_size = 256,
    patch_size = 32,
    num_classes = 1000,
    dim = 1024,
    depth = 6,
    heads = 16,
    mlp_dim = 2048,
    dropout = 0.1,
    emb_dropout = 0.1
)

img = torch.randn(1, 3, 256, 256)

preds = v(img) # (1, 1000)
'''

class FeedForward(nn.Module):
    '''
        放大->提取->缩小
    '''
    def __init__(self, dim, hidden_dim, dropout = 0.):
        super().__init__()
        self.net = nn.Sequential(
            nn.LayerNorm(dim),
            nn.Linear(dim, hidden_dim), # hidden_dim 隐藏层
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, dim),
            nn.Dropout(dropout)
        )

    def forward(self, x):
        return self.net(x)

class Attention(nn.Module):
    def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
        super().__init__()
        inner_dim = dim_head *  heads
        project_out = not (heads == 1 and dim_head == dim)

        self.heads = heads
        self.scale = dim_head ** -0.5

        self.norm = nn.LayerNorm(dim)

        self.attend = nn.Softmax(dim = -1)
        self.dropout = nn.Dropout(dropout)

        self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) # 对于qkv进行一次行定义下来。直接乘三

        self.to_out = nn.Sequential(
            nn.Linear(inner_dim, dim),
            nn.Dropout(dropout)
        ) if project_out else nn.Identity()

    def forward(self, x):
        x = self.norm(x)

        qkv = self.to_qkv(x).chunk(3, dim = -1) # 将刚刚qkv的乘三分开，分为三个向量
        q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
        # 将inner_dim拆分为heads × dim_head，最终q, k, v形状为(b, h, n, d)（h=heads，d=dim_head）。

        # Q与K的转置矩阵相乘：(b, h, n, d) × (b, h, d, n) → (b, h, n, n)
        dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale # (q * K)*d_k**-0.5

        # 归一化 softmax+dropout
        attn = self.attend(dots)
        attn = self.dropout(attn)

        # 计算结果与V相乘
        out = torch.matmul(attn, v)

        # 将松散的数据connect在一起
        out = rearrange(out, 'b h n d -> b n (h d)')
        return self.to_out(out)



class Transformer(nn.Module):
    def  __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.layers = nn.ModuleList([])
        for _ in range(depth): # 循环次数（层数）
            self.layers.append(nn.ModuleList([
                # 自注意力层
                Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout),
                # 前馈神经网络
                FeedForward(dim, mlp_dim, dropout = dropout)
            ]))

    def forward(self, x):
        for attn, ff in self.layers:

            #
            x = attn(x) + x
            x = ff(x) + x

        return self.norm(x)

class ViT(nn.Module):
    def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, pool = 'cls', channels = 3, dim_head = 64, dropout = 0., emb_dropout = 0.):
        super().__init__()
        image_height, image_width = pair(image_size)
        patch_height, patch_width = pair(patch_size)

        assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'

        num_patches = (image_height // patch_height) * (image_width // patch_width)
        patch_dim = channels * patch_height * patch_width
        assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)'

        '''
        # 讲一个图片切成不同Patch的详细步骤
        img = torch.randn(1,3,256,256)
        b = 1
        c = 3
        h = 256 = h * p1 -> 假如patch_height = 8; 所以p1 = 32.即把这整个图片切分为32个行
        w = 256
        
        b (h w) (p1 p2 c) ->224×224 图像分块后，h*w=32×32个图像块，每个展平为8×8×3维，输出形状为(b, 32*32, 8*8*3)。
        '''
        self.to_patch_embedding = nn.Sequential(
            Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),
            nn.LayerNorm(patch_dim),
            nn.Linear(patch_dim, dim),# 线性投影到目标嵌入维度
            nn.LayerNorm(dim),
        )

        self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))
        self.cls_token = nn.Parameter(torch.randn(1, 1, dim)) # (batch_size = 1,token = 1,dim = dim是为了更好加)
        self.dropout = nn.Dropout(emb_dropout)

        self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)

        self.pool = pool
        self.to_latent = nn.Identity()

        self.mlp_head = nn.Linear(dim, num_classes)

    def forward(self, img):
        x = self.to_patch_embedding(img) # 将一个图片切开成好多个patch
        b, n, _ = x.shape

        cls_tokens = repeat(self.cls_token, '1 1 d -> b 1 d', b = b) # 让1进行占位，重复batch-size个token，让每个都有一个
        print("cls_tokens:", cls_tokens.shape)
        x = torch.cat((cls_tokens, x), dim=1) # 让每个token和每个图片的个数相互拼接。
        print("x+tokens:",x.shape)
        print("pos_embedding:",self.pos_embedding.shape)
        x += self.pos_embedding[:, :(n + 1)]  # 将位置信息添加进来
        print("x+pos_embedding:",x.shape)
        x = self.dropout(x) # 正则
        print("x+dropout:",x.shape)

        '''
        cls_tokens: torch.Size([1, 1, 1024])
        x+tokens: torch.Size([1, 65, 1024])
        pos_embedding: torch.Size([1, 65, 1024])
        x+pos_embedding: torch.Size([1, 65, 1024])
        x+dropout: torch.Size([1, 65, 1024])
        '''

        x = self.transformer(x)

        x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]

        x = self.to_latent(x)
        return self.mlp_head(x)
